#coding=utf-8
import json
import sys
import os  
import os.path  
import shutil
import platform
from PIL import Image

pngquantPath = os.path.join(sys.path[0],"pngquant/pngquant.exe")
sysstr = platform.system()
if(sysstr =="Windows"):
	print ("Windows System support")
	pngquantPath = os.path.join(sys.path[0],"pngquant/pngquant.exe")
elif(sysstr == "Linux" or sysstr == "Darwin"):
	print ("Linux  Darwin System support")
	pngquantPath = os.path.join(sys.path[0],"pngquant/pngquant")
else:
    print ("Other System not support",sysstr)

def getFilesAbsolutelyPath(path):  
    currentfiles = os.listdir(path)  
    filesVector = []  
    for file_name in currentfiles:  
        fullPath = os.path.join(path, file_name)  
        if os.path.isdir(fullPath):  
            newfiles = getFilesAbsolutelyPath(fullPath)  
            filesVector.extend(newfiles)  
        else:  
            filesVector.append(fullPath)  
    return filesVector  
def doQuantWithPath(fromPath):
	filePathVector = getFilesAbsolutelyPath(fromPath)  
	totalReleaseCount = 0;
	for filename in filePathVector:  
		if os.path.splitext(filename)[1] == ".png":  
			im = Image.open(filename)
			if im.mode != "P":  
				totalReleaseCount += pngquantPng(pngquantPath,filename)
	return totalReleaseCount
# 压缩图片
def pngquantPng(pngquantExePath,filename):
	os.system(pngquantExePath +" -f --ext new.png --quality 50-80 "+ filename)  
	(shotname,extension) = os.path.splitext(filename);
	newFileName = shotname+"new"+extension;
	orgSize,orgCount = getFileSize(filename)
	if os.path.isfile(newFileName):
		shutil.copy2(newFileName,filename)
		os.remove(newFileName)
	afterSize,afterCount = getFileSize(filename)
	print getUtf8String("压缩图片======"),filename,orgSize,"=============>",afterSize
	return orgCount-afterCount
def getFileSize(filename):
	count = os.path.getsize(filename)
	if os.path.isfile(filename):
		return '%.2f'% (count/1024.0)+'KB',count
	return "0K",0
def getUtf8String(string):
	if(sysstr =="Windows"):
		string = string.decode('utf-8').encode('gbk')
	elif(sysstr == "Linux" or sysstr == "Darwin"):
		string = string.decode('utf-8')
	else:
	    string = string.decode('utf-8')
	return string
if __name__=="__main__":
	print getUtf8String("=========================开始压缩============================")
	inputJsonFile = "pngquantPngConfig.json"
	fin = open(inputJsonFile, 'r')
	jsonobj = json.load(fin)
	fin.close()
	paths = jsonobj["paths"]
	releaseCount = 0#总共压缩了多少
	for path in paths:
		releaseCount += doQuantWithPath(path)
	print getUtf8String("=========================压缩完成============================")
	print getUtf8String("总共压缩================="),'%.2f'% (releaseCount/1024.0)+'KB'
	if len(sys.argv) == 1:
		raw_input()
